What is common-path-prefix?
The 'common-path-prefix' npm package is a utility that helps in finding the longest common path prefix from an array of file paths. This can be particularly useful in scenarios where you need to determine the shared directory structure among multiple files.
What are common-path-prefix's main functionalities?
Finding Common Path Prefix
This feature allows you to find the longest common path prefix from an array of file paths. In the provided code sample, the common prefix for the given paths is '/foo/bar'.
const commonPathPrefix = require('common-path-prefix');
const paths = ['/foo/bar/baz', '/foo/bar/qux', '/foo/bar/quux'];
const prefix = commonPathPrefix(paths);
console.log(prefix); // Output: '/foo/bar'
Other packages similar to common-path-prefix
path
The 'path' module is a core Node.js module that provides utilities for working with file and directory paths. While it does not directly offer a method to find the common path prefix, it provides various methods to manipulate and analyze paths, which can be used in conjunction to achieve similar results.
lodash
Lodash is a utility library that provides a wide range of functions for common programming tasks. While it does not specifically focus on path manipulation, it includes methods for working with arrays and strings that can be used to implement similar functionality.
common-path-prefix
Computes the longest prefix string that is common to each path, excluding the base component. Tested with Node.js 8 and above.
Installation
npm install common-path-prefix
Usage
The module has one default export, the commonPathPrefix
function:
const commonPathPrefix = require('common-path-prefix')
Call commonPathPrefix()
with an array of paths (strings) and an optional separator character:
const paths = ['templates/main.handlebars', 'templates/_partial.handlebars']
commonPathPrefix(paths, '/')
If the separator is not provided the first /
or \
found in any of the paths is used. Otherwise the platform-default value is used:
commonPathPrefix(['templates/main.handlebars', 'templates/_partial.handlebars'])
commonPathPrefix(['templates\\main.handlebars', 'templates\\_partial.handlebars'])
You can provide any separator, for example:
commonPathPrefix(['foo$bar', 'foo$baz'], '$')
An empty string is returned if no common prefix exists:
commonPathPrefix(['foo/bar', 'baz/qux'])
commonPathPrefix(['foo/bar'])
Note that the following does have a common prefix:
commonPathPrefix(['/foo/bar', '/baz/qux'])